<template>
	<el-dialog title="选择试题" :visible.sync="visible" width="992px" top="0" append-to-body custom-class="subject_select_dialog">
		<sw-tabs v-model="permission" :options="permissionTypes" @change="handleQueryTableData()" />
		<el-form size="mini" inline class="subject_query">
			<el-form-item>
				<el-select v-model="queryData.bankId" clearable placeholder="请选择题库" style="width: 240px">
					<el-option v-for="(item, index) in topicLibraryData" :key="index" :label="item.name" :value="item.id">
						<font color="#303133">{{ item.name }}</font>
						<font color="#909399">{{ item.permission | permissionFilter }}</font>
					</el-option>
				</el-select>
			</el-form-item>
			<el-form-item>
				<el-input v-model="queryData.title" clearable placeholder="请输入题干" style="width: 200px"></el-input>
			</el-form-item>
			<el-form-item>
				<el-input v-model="queryData.tags" clearable placeholder="请输入标签" style="width: 200px"></el-input>
			</el-form-item>
			<el-form-item>
				<el-select v-model="queryData.type" clearable placeholder="请选择类型">
					<el-option v-for="(item, index) in subjectTypes" :key="index" :label="item.label" :value="item.value" />
				</el-select>
			</el-form-item>
			<el-form-item>
				<el-select v-model="queryData.difficulty" clearable placeholder="请选择难度">
					<el-option v-for="(item, index) in subjectDifficulty" :key="index" :label="item.label" :value="item.value" />
				</el-select>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" @click="handleQueryTableData()">查询</el-button>
			</el-form-item>
		</el-form>
		<el-table v-bind="tableConfig" :data="tableListData" @row-click="handleRowClick" @select-all="handleSelectAllChange">
			<el-table-column type="selection" width="42" align="center" />
			<el-table-column label="题库" prop="bank" min-width="160" show-overflow-tooltip>
				<template slot-scope="{ row }">{{ row.testQuestionBank.name }}</template>
			</el-table-column>
			<el-table-column label="题库名称" prop="title" min-width="320" show-overflow-tooltip>
				<div class="library-name" slot-scope="{ row }" v-html="$removeEmptyTag($cleanStyle(row.title))" />
			</el-table-column>
			<el-table-column label="标签" prop="tags" min-width="200" show-overflow-tooltip />
			<el-table-column label="类型" width="80" align="center" :formatter="returnTypeName" />
			<el-table-column label="难度" width="80" align="center" :formatter="returnDifficultyName" />
			<el-table-column label="操作" width="60">
				<template slot-scope="{ row }">
					<el-button type="text" @click.stop="handleLookSubject(row)">详情</el-button>
				</template>
			</el-table-column>
		</el-table>
		<sw-pagination :total="dataCount" :page.sync="queryData.page" :limit.sync="queryData.limit" @change="queryTableData()" />
		<template slot="footer">
			<el-button size="medium" @click="visible = false">取消</el-button>
			<el-button size="medium" type="primary" @click="handleConfirmSelect()">确定</el-button>
		</template>
	</el-dialog>
</template>

<script>
import { getQuestionsList } from '@/api/exam/testSubjects';
import { getTopicLibraryList } from '@/api/exam/testQuestionBank';
import { subjectType, subjectDifficulty } from '@/utils/subjectData';
export default {
	inject: ['subjectBanks'],
	props: {
		value: { type: Boolean, default: false },
		list: { type: Array, default: () => [] },
		chapterId: { type: String, default: '' }
	},
	data() {
		return {
			visible: this.value,
			tableConfig: {
				ref: 'table',
				rowKey: 'id',
				height: '100%',
				class: 'subject_table'
			},
			queryData: { page: 1, limit: 10 },
			checkedIds: new Set(),
			checkedSubject: [],
			tableListData: [],
			permission: '1',
			loading: false,
			dataCount: 0,
			permissionTypes: [
				{ id: '1', label: '我的试题' },
				{ id: '2', label: '共享试题' }
			]
		};
	},
	computed: {
		subjectTypes() {
			return subjectType;
		},
		subjectDifficulty() {
			return subjectDifficulty;
		},
		topicLibraryData() {
			return this.subjectBanks();
		}
	},
	filters: {
		permissionFilter(val) {
			return val === '1' ? '私有' : val === '2' ? '共享' : '';
		}
	},
	watch: {
		value(flag) {
			this.visible = flag;
		},
		async visible(flag) {
			this.$emit('input', flag);
			if (!flag) return false;
			this.permission = '1';
			this.checkedIds.clear();
			this.checkedSubject = [];
			this.list.forEach((data) => {
				if (this.checkedIds.has(data.id)) return false;
				this.checkedSubject.push(data.testSubjects);
				this.checkedIds.add(data.id);
			});
			this.queryTableData();
		},
		tableListData(arr) {
			this.$nextTick(() => {
				if (!this.$refs['table']) return false;
				this.$refs['table'].clearSelection();
				this.tableListData.forEach((row) => {
					if (!this.checkedIds.has(row.id)) return false;
					this.$refs['table'].toggleRowSelection(row, true);
				});
			});
		}
	},
	methods: {
		//获取试题数据
		async getSubjectData() {
			let params = { ...this.queryData, subjectsPermission: this.permission };
			let result = await getQuestionsList(params).then((res) => res.data);
			this.loading = false;
			if (result.code === '0') {
				this.dataCount = parseInt(result.count);
				this.tableListData = result.data || [];
			}
		},

		//查询试题数据
		queryTableData() {
			this.loading = true;
			this.getSubjectData();
		},

		//查询试题
		handleQueryTableData() {
			this.queryData.page = 1;
			this.queryTableData();
		},

		handleLookSubject(data) {
			this.$bus.$emit('lookSubject', data.id);
		},

		returnTypeName(data) {
			let info = subjectType.find((n) => n.value === data.type);
			return !info ? '--' : info.label;
		},

		returnDifficultyName(data) {
			let style = {};
			let attrs = { size: 'small', effect: 'plain' };
			let info = subjectDifficulty.find((n) => {
				return n.value === data.difficulty;
			});
			if (!info) {
				attrs['type'] = 'info';
			} else if (info.value === '1') {
				style['--tag-color'] = '#67C23A';
			} else if (info.value === '2') {
				style['--tag-color'] = '#95D448';
			} else if (info.value === '3') {
				style['--tag-color'] = '#E6A740';
			} else if (info.value === '4') {
				style['--tag-color'] = '#F18750';
			} else if (info.value === '5') {
				style['--tag-color'] = '#F56C6C';
			}
			return this.$createElement('elTag', { attrs, style }, info?.label || '未知');
		},

		handleRowClick(row, column, event) {
			let columns = ['bank', 'title', 'tags'];
			if (columns.includes(column.property) || column.type === 'selection') {
				if (!this.checkedIds.has(row.id)) {
					this.$refs['table'].toggleRowSelection(row, true);
					this.checkedSubject.push(row);
					this.checkedIds.add(row.id);
				} else {
					let index = this.checkedSubject.findIndex((n) => n.id === row.id);
					this.$refs['table'].toggleRowSelection(row, false);
					this.checkedSubject.splice(index, 1);
					this.checkedIds.delete(row.id);
				}
			}
		},

		handleSelectAllChange(selection) {
			if (selection.length === 0) {
				this.tableListData.forEach((item) => {
					let index = this.checkedSubject.findIndex((n) => n.id === item.id);
					this.checkedSubject.splice(index, 1);
					this.checkedIds.delete(item.id);
				});
			} else {
				selection.forEach((item) => {
					if (this.checkedIds.has(item.id)) return false;
					this.checkedSubject.push(item);
					this.checkedIds.add(item.id);
				});
			}
		},

		//确定选中试题
		handleConfirmSelect() {
			this.$bus.$emit('checkedSubject', this.checkedSubject, this.chapterId);
			this.visible = false;
		}
	}
};
</script>
<style lang="scss">
.subject_select_dialog {
	.el-dialog__body {
		padding: 0;
		flex-direction: column;
		height: calc(100vh - 244px);
	}
	.sw-pagination {
		padding: 10px;
	}
}
</style>
<style lang="scss" scoped>
.subject_header {
	display: flex;
	height: 40px;
	line-height: 40px;
	text-align: center;
	border-bottom: solid 1px #e4e7ed;
	span {
		flex: 1;
		font-size: 15px;
		overflow: hidden;
		border-left: solid 1px #e4e7ed;
		user-select: none;
		cursor: pointer;
		&:first-child {
			border-left: 0;
		}
		&.active {
			font-weight: bold;
			color: var(--primary-active);
			background-color: var(--primary-background-hover);
		}
	}
}
.subject_query {
	padding: 10px;
}
.subject_table::v-deep {
	flex: 1;
	overflow: hidden;
	border-top: solid 1px #e4e7ed;
	.library-name {
		overflow: hidden;
		white-space: nowrap;
		text-overflow: ellipsis;
	}
	.el-button {
		padding: 6px 0;
	}
	.el-table__cell {
		line-height: 1;
		.cell {
			line-height: 1;
		}
	}
	th.el-table__cell {
		background-color: #f2f6fc;
		.cell {
			font-size: 15px;
		}
	}
	td.el-table__cell {
		&.el-table-column--selection {
			font-size: 0;
		}
		&:nth-child(-n + 4) {
			cursor: pointer;
		}
		.el-checkbox {
			pointer-events: none;
		}
	}
	.el-tag.el-tag--plain {
		color: var(--tag-color);
		border-color: var(--tag-color);
	}
}
</style>
